<template>		<!--该页面为测试记录页面-->
	<div>
		<el-breadcrumb separator="/"> <!--面包屑 -->
      <el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>点检记录</el-breadcrumb-item>
    </el-breadcrumb>
		<div class="info">
			<el-card shadow="always">
				<div slot="header" class="clearfix">
				<el-form ref="form" :model="searchContent" label-width="80px"  size="small">
				<el-row>
					<el-col :span="8">
						<el-form-item label="设备名称">
							<el-input v-model="searchContent.instr_name" placeholder="请输入设备名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="设备型号">
							<el-input v-model="searchContent.model"  placeholder="请输入设备型号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="设备编号">
							<el-input v-model="searchContent.instr_number"  placeholder="请输入设备编号" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row style="position:relative;">
					<el-col :span="8">
						 <el-form-item label="点检月份">
								<el-date-picker
									v-model="timeSelect"
									type="month"
									:placeholder="timeSelect"
									:clearable="false"
									style="width:100%;"
									value-format="yyyy-MM"
									@change="autoSearch" >
								</el-date-picker>
								</el-form-item>
					</el-col>
					<el-col :span="8" :offset="8">
						<el-form-item style="float: right">
							<el-button type="primary"  @click="toSerach" size="small">查询</el-button>
							<el-button class="textBtn" size="small" @click="reset">重置</el-button>
						</el-form-item>
					</el-col>
				</el-row>
				</el-form>
				</div>
			<!-- </el-card>

			<el-card shadow="always" style="margin-top: 30px"> -->
				<el-row style="float:right; margin-right: 15px;margin-bottom: 5px;">
					<el-dropdown @command="exportDeviceInfo">
						<el-button class="global_add" type="text" :disabled="btnList.exportList"  size="small" >↓&nbsp;导出记录</el-button>
						<el-dropdown-menu slot="dropdown">
									<el-dropdown-item :disabled="btnList.export" command="selection">导出选中</el-dropdown-item>
									<el-dropdown-item :disabled="btnList.export" command="allInfo">导出全部</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</el-row>
				<el-table @sort-change='sortChange' stripe v-loading="dataLoading" :data="checkRecordData.slice((currentPage-1)*pagesize,currentPage*pagesize)" row-key="instr_id" ref="multipleTable" style="width: 100%" @selection-change="handleSelectionChange">>
					<el-table-column type="selection" width="55" reserve-selection></el-table-column>
					<el-table-column type="index" :index = '(index) =>{return (index + 1) + (currentPage - 1) * pagesize}' label="#" width="70" align="center"></el-table-column>
					<el-table-column sortable align="center" prop="instr_name" label="设备名称" show-overflow-tooltip></el-table-column>
					<el-table-column sortable align="center" prop="model" label="设备型号" show-overflow-tooltip></el-table-column>
					<el-table-column sortable align="center" prop="instr_number" label="设备编号" show-overflow-tooltip></el-table-column>
					<el-table-column sortable align="center" prop="spec" label="规格" show-overflow-tooltip></el-table-column>
					<el-table-column sortable align="center" prop="station_name" label="工位名称" show-overflow-tooltip></el-table-column>
					<el-table-column align="center"  label="操作" >
						<template slot-scope="scope">
              <el-button class="global_add" @click="preview(scope.$index, scope.row)" type="text" size="small" style="color: #6d6fe9">查看</el-button>
							<el-button class="global_add" type="text" size="small" :disabled="btnList.exportOne" @click="outPutOne(scope.$index, scope.row)" style="color:#6d6fe9" >导出</el-button>
						</template> 
					</el-table-column>
				</el-table>
				<el-pagination class="pagination" background :hide-on-single-page="showPagination" :current-page.sync="currentPage" @size-change="handleSizeChange" :page-size="pagesize" layout="prev, pager, next" :total="checkRecordData.length"></el-pagination>
			</el-card>
		</div>
	</div>
</template>
<script>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 引入需要用到的第三方nodejs库，如日期计算等
// 需要先通过npm安装第三方组件包，然后在代码中使用
// npm install xxx 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import moment from 'moment';
import dayjs from 'dayjs';
import sessionStorage from '../../public/storage.js';
import roleBtn from '../../public/means'
import { base64 } from '../../public/base64'
import { serverURL,gkServerURL } from '../../public/setting'
export default {
	data() {
		return {
			timeSelect: '',				//时间选择
			timeOfNow:'',
			searchContent: {
				instr_name :'',
				model:'',
				instr_number:'',
			},	//搜索
			checkRecordData: [],
			multipleSelection: [],
			showPagination: true,
			currentPage: 1,
      pagesize: 10,
			dataLoading: false,
			menu_id: 13,
      btnList: {
        exportList: false,
        exportOne: false,
      },
		};
	},
	methods: {
		generalSort(attr, rev){
			//第一个参数传入表示排的是哪一列，第二个参数是升还是降排序
			console.log(1);
			if (rev == undefined) {
				rev = 1;
			} else {
				rev = (rev) ? 1 : -1;
			}
			return function (arry, barry) {
				arry = arry[attr];
				barry = barry[attr];
				if(arry === null){
					return rev * 1;
				}	
				if (arry < barry) {
					return rev * -1;
				}
				if (arry > barry) {
					return rev * 1;
				}
				return 0;
			}
		},
		// 表格排序问题
		sortChange(column){
			this.currentPage = 1;
			if (column.prop === 'instr_name') {
				this.checkRecordData = this.checkRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			} else if (column.prop === 'model') {
				this.checkRecordData = this.checkRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			} else if (column.prop === 'instr_number') {
				this.checkRecordData = this.checkRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			} else if (column.prop === 'spec') {
				this.checkRecordData = this.checkRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			} else if (column.prop === 'station_name') {
				this.checkRecordData = this.checkRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			}
			this.checkRecordData = this.checkRecordData.slice(0, this.pageSize) // 排序完显示到第一页
		},
		//	导出设备信息
		async exportDeviceInfo(command) {
			if (command === 'selection') {
				if (this.multipleSelection.length === 0) {
				this.$message.error('请勾选需要导出的数据！');
				return
				}
				this.outPutMultiple()
			} else {
				this.multipleSelection = this.checkRecordData
				this.outPutMultiple()
				}
			},
		autoSearch(){
			this.toSerach();
		},
		toSerach(){
			//let checkResult=this.toCheckTimeSelect();
			//if(checkResult){
				//this.timeSelect = this.timeOfNow ;
			//}
			console.info(this.timeSelect);
			this.getAllCheckRecord();
		},
		toCheckTimeSelect(){
			if(this.timeSelect==null||this.timeSelect==''){
				this.$message.closeAll();
				this.$message({ message: '请选择月份！', type: 'error', duration: 2000 });
				return false;
			}else{
				var date = new Date();
				var year=date.getFullYear();
				var month=date.getMonth()+1;
				if(this.timeSelect.split("-")[0]<year){
					return true;
				}else if(this.timeSelect.split("-")[0]>year){
					this.$message.closeAll();
				  this.$message({ message: '请选择已有点检记录的日期！', type: 'error', duration: 2000 });
					return false;
				}else if(this.timeSelect.split("-")[0]==year&&this.timeSelect.split("-")[1]>month){
					this.$message.closeAll();
				  this.$message({ message: '请选择已有点检记录的日期！', type: 'error', duration: 2000 });
					return false;
				}else
					return true;
			}
		},
		async previewAndGenerateFile(instrName,instrId,instrNumber,timeSelect){
			const params = {
				'instrName': instrName,
				'instrId':instrId,
				'instrNumber':instrNumber,
				'timeSelect':timeSelect
			}
			const ret =  await this.$http.post(gkServerURL + "/checkRecord/writeReport",params);
			const res =  await this.$http.post("/checkRecord/writeReport",params);
			return res;
		},
    async preview(index,row){
			const loading = this.$loading({
				lock: true,
				text: '加载中，请稍后',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)',
				customClass: 'londing_class'
				});
				const res = await this.previewAndGenerateFile(row.instr_name,row.instr_id,row.instr_number,this.timeSelect);
				if(res.code === 200){
					var url = gkServerURL + "/public/report/"+res.pdfFile;
					// window.open("http://123.56.132.202:8012/onlinePreview?url=" + encodeURIComponent(base64.encode(url))); // 先打开页面
					loading.close();
					window.open(url)
				} else {//http://123.56.132.202:8130/public/report/template/template.docx
					loading.close();
				}
		},
		async outPutOne(index,row){
			const loading = this.$loading({
				lock: true,
				text: '导出中，请稍后',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)',
				customClass: 'londing_class'
				});
				const res = await this.previewAndGenerateFile(row.instr_name,row.instr_id,row.instr_number,this.timeSelect);
				if(res.code === 200){
					this.$message({
						message: res.message,
						type: 'success'
					});
					loading.close();
					location.href = gkServerURL + '/public/report/'+res.docxFile ;
				} else {
					loading.close();
				}
		},
		reset(){
			this.searchContent.instr_name='';
			this.searchContent.instr_number='';
			this.searchContent.model='';
			this.timeSelect=this.timeOfNow;
			//this.timeSelect='';
		},
		toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
    },
	async	outPutMultiple(){
			if(this.multipleSelection.length==0){
				this.$message.closeAll();
				this.$message({ message: '请选择导出设备！', type: 'error', duration: 1000 });
			}else{
					for(let i=0;i<this.multipleSelection.length;i++){
						const res = await this.previewAndGenerateFile(this.multipleSelection[i].instr_name,this.multipleSelection[i].instr_id,this.multipleSelection[i].instr_number,this.timeSelect)
						if(res.code === 200){
							this.$message({
								message: res.message,
								type: 'success'
							});
							location.href = gkServerURL +  '/public/report/'+res.docxFile ; 
						}
					}	
			}
		},
		handleSelectionChange(val) {
			this.multipleSelection = val; 
		},
		handleSizeChange(val) {
      this.pagesize=val;
		},
		
		//获取统计记录
		async getAllCheckRecord(){
			this.dataLoading = true;
			const params = {
        'instrName': this.searchContent.instr_name,
				'instrNumber':this.searchContent.instr_number,
				'model':this.searchContent.model,
				'checkDate':this.timeSelect
      }
			const ret = await this.$http.get("/checkRecord/getAllCheckRecord",{params,});
			this.checkRecordData=ret.result;
			this.dataLoading = false;
		},
	},
	mounted() {
		let date=new Date();
    let year=date.getFullYear();
    let month=date.getMonth()+1;
		if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
		this.timeOfNow=year+"-"+month;
		this.timeSelect=this.timeOfNow;
		this.getAllCheckRecord();
	},
  async created() {
    const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
      // 获取按钮权限状态
      let arr = await roleBtn.roleBtnList(role_id, this.menu_id)
      this.btnList = arr
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./CheckRecord.scss";
</style>